﻿using Bricks.Business.Models.Account;
using Bricks.Business.Service;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Bricks.Component.Utils;
using Bricks.Component.Utils.Extensions;
using Bricks.Site.Models.Purview;
using Bricks.Business.Models.BidManagement;
using Bricks.Business.Service.CommonSupport;
using Bricks.Site.Models.BidInfo;
using Bricks.Business.Models.Document;
using Bricks.Site.Models.Document;
using System.Text;
using System.IO;

namespace Bricks.Site.Web.Controllers
{
    /// <summary>
    /// 文档管理
    /// </summary>
    [Export]
    public class DocumentController : BaseController
    {
        [Import]
        public IDocumentService DocumentService { get; set; }

        /// <summary>
        /// 首页
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            ////取得面板及工具栏信息
            //ViewBag.PanelInfo = base.GetPanelInfo();
            //ViewBag.ToolBarInfo = base.GetToolBarInfo();
            return View();
        }

        #region 通用附件操作
        /// <summary>
        /// 操作
        /// </summary>
        /// <param name="instanceID"></param>
        /// <param name="tag"></param>
        /// <returns></returns>
        public ActionResult DocumentList(string instanceID, string tag, bool btnDisabled = false)
        {
            ViewBag.InstanceID = instanceID;
            ViewBag.Tag = tag;
            ViewBag.BtnDisabled = btnDisabled;
            ViewBag.CurrentUserID = SystemData.Instance.CurrentUser.ID;
            ViewBag.CurrentUser = SystemData.Instance.CurrentUser.UserName;
            return View();
        }

        /// <summary>
        /// 获取文档列表
        /// </summary>
        /// <param name="instanceID"></param>
        /// <param name="tag"></param>
        /// <returns></returns>
        public ActionResult GetDocumentList(string instanceID, string tag)
        {
            Guid instanceGuid = instanceID.ToGuid();

            var list = from document in DocumentService.Documents
                       join user in UserInfoService.Users on document.UploadUserID equals user.ID into userJoin
                       from userLeft in userJoin.DefaultIfEmpty()  //防止用户已经丢失
                       where document.InstanceID == instanceGuid && document.Tag == tag
                       select new DocumentView
                       {
                           FileName = document.FileName,
                           FilePath = document.FilePath,
                           FileSize = document.FileSize,
                           UploadUserID = document.UploadUserID,
                           UploadUser = userLeft.UserName,
                           //AddDate = document.AddDate
                           UploadTime = document.UploadTime
                       };
            return Json(list);
        }

        [HttpPost]
        public ActionResult SavePost()
        {
            var result = new OperationResult(OperationResultType.Success, "文件操作成功");
            return Json(result, "text/html");
        }

        /// <summary>
        /// 保存附件列表（通用附件上传控件）
        /// </summary>
        /// <param name="instanceID"></param>
        /// <param name="tag"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SaveDocumentPost(string instanceID, string tag)
        {
            //undefined
            string data = Request.Form["Data"];
            List<DocumentView> list = JsonHelper.JsonDeserialize<List<DocumentView>>(data);
            OperationResult result = DocumentService.SaveDocumentList(instanceID.ToGuid(), tag, list);
            return Json(result, "text/html");
        }

        /// <summary>
        /// 保存通过ueditor编辑器上传的附件列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SaveRichTextBoxDocumentPost(string instanceID, string attachmentTag)
        {
            string data = Request.Form["Data"];
            List<UEditorDocumentView> list = JsonHelper.JsonDeserialize<List<UEditorDocumentView>>(data);
            OperationResult result = DocumentService.SaveRichTextBoxDocumentList(list, instanceID.ToGuid(), attachmentTag);
            return Json(result, "text/html");
        }
        #endregion

        /// <summary>
        /// 获取所有文档（文档列表）
        /// </summary>
        /// <param name="rows"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        public ActionResult GetAllDocumentList(string modelID, string menuID, int rows = 20, int page = 1)
        {
            //var data = DocumentService.Documents.OrderByDescending(m => m.AddDate).Skip(rows * (page - 1)).Take(rows).ToList();  //根据上传时间降序排序
            //var list = from m in data
            //           select new
            //           {
            //               ID = m.ID,
            //               FileName = m.FileName,
            //               FilePath = m.FilePath,
            //               FileSize = m.FileSize,
            //               UploadUser = UserInfoService.GetUserNameByID(m.UploadUserID),
            //               Tag = m.Tag,
            //               UploadTime = m.UploadTime
            //           };
            //var result = new { total = DocumentService.Documents.Count(), rows = list };
            //return Json(result, JsonRequestBehavior.AllowGet);

            var data = DocumentService.Documents;
            //此处可能根据模块或者菜单进行筛选查询
            if (!String.IsNullOrEmpty(modelID))
            {
                string tagSearch = string.Empty;  //Tag搜索文本
                MenuInfo model = MenuInfoService.GetMenuInfo(modelID.ToGuid());
                if (model != null)
                {
                    tagSearch = model.MenuCode;
                    //如果传入了查找菜单ID
                    if (!String.IsNullOrEmpty(menuID))
                    {
                        MenuInfo menu = MenuInfoService.GetMenuInfo(menuID.ToGuid());
                        if (menu != null)
                        {
                            tagSearch += "/" + menu.MenuCode;  //构造格式eg：模块/菜单
                        }
                    }
                    data = data.Where(m => m.Tag.StartsWith(tagSearch));
                }
            }
            List<DocumentInfo> dataList = data.OrderByDescending(m => m.UploadTime).Skip(rows * (page - 1)).Take(rows).ToList();  //根据上传时间降序排序
            var list = from m in dataList
                       select new
                       {
                           ID = m.ID,
                           FileName = m.FileName,
                           FilePath = m.FilePath,
                           FileSize = m.FileSize,
                           UploadUser = UserInfoService.GetUserNameByID(m.UploadUserID),
                           //Tag = m.Tag,
                           //ModelName = MenuInfoService.GetModelAndMenuName(m.Tag).Item1,
                           //MenuName = MenuInfoService.GetModelAndMenuName(m.Tag).Item2,
                           ModelAndMenuName = MenuInfoService.GetModelAndMenuName(m.Tag),
                           UploadTime = m.UploadTime
                       };
            var result = new { total = DocumentService.Documents.Count(), rows = list };
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 批量删除文档
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult Delete(string ids)
        {
            var result = new OperationResult(OperationResultType.NoChanged, "无记录变化");
            if (!String.IsNullOrEmpty(ids))
            {
                string[] idsArray = ids.Split(',');
                if (idsArray != null && idsArray.Length > 0)
                {
                    List<Guid> guids = new List<Guid>();
                    foreach (string id in idsArray)
                    {
                        guids.Add(id.ToGuid());
                    }
                    result = DocumentService.Delete(guids);
                }
            }
            return Json(result);
        }

        /// <summary>
        /// 下载
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public ActionResult DownLoad(string filePath, string fileName)
        {
            //Response.ContentEncoding = Encoding.UTF8;
            //Response.ContentType = "application/octet-stream";
            //Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
            //Response.Redirect(filePath);

            byte[] bytes = new byte[256];
            string path = Server.MapPath(filePath);
            FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
            //用于文件另存为
            Response.ContentType = "application/octet-stream";
            //将弹出窗体的文件名，显示为文件原始名称
            Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
            Response.AppendHeader("Content-Length", stream.Length.ToString());
            //文件总长度
            int totalLength = Convert.ToInt32(stream.Length);

            if (Response.IsClientConnected)
            {
                while (totalLength > -1)
                {
                    totalLength = totalLength - bytes.Length;
                    stream.Read(bytes, 0, bytes.Length);
                    Response.OutputStream.Write(bytes, 0, bytes.Length);
                }
            }
            stream.Close();
            return null;
        }
    }
}
